package com.bluefox.hospital.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author Administrator
 */
public class UploadAndDeleteFile {
    public static List<Map<String,Object>> upload(HttpServletRequest servletRequest,String uploadAnyWhere) {
    	MultipartHttpServletRequest request = (MultipartHttpServletRequest) servletRequest;
        Iterator<String> itr = request.getFileNames();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        try {
        	File directory = new File(uploadAnyWhere);
        	if(!directory.exists()) {
        		directory.mkdirs();
        	}
            String courseFile = directory.getCanonicalPath();
        	MultipartFile proFile = null;
            while (itr.hasNext()) {
                String str = itr.next();
                proFile = request.getFile(str);
                // 将名字改为UUID
                String file_uid = UUID.randomUUID().toString();
                String suffix = proFile.getOriginalFilename();
                //suffix.substring(suffix.lastIndexOf("."))
                File file = new File(courseFile+"/"+file_uid+suffix.substring(suffix.lastIndexOf(".")));
                proFile.transferTo(file);
                Map<String,Object> map = new HashMap<String, Object>();
                map.put("name", proFile.getOriginalFilename());
                String path = file.getAbsolutePath().replace('\\', '/');;
                map.put("url", path);
                map.put("status","success");
                list.add(map);
            }
		} catch (IOException e) {
			e.printStackTrace();
		}
        return list;
    }

    public static boolean deleteFile(final String path) {
    	File directory = new File(path);// 参数为空
    	return directory.delete();
    }

}
